<?php

namespace Xnrcms\BaseTools;

use Exception;

/**
 * 常用工具函数
 */
class Fun
{
    /**
     * 生成随机数
     * @param number $length 字符串长度
     * @param int $type 字符串类型
     * @return string
     * @throws Exception
     */
    public static function randomString($length, int $type = 0): string
    {
        $arr  = [
            0 => '0123456789',
            1 => 'abcdefghjkmnpqrstuxy',
            2 => 'ABCDEFGHJKMNPQRSTUXY',
            3 => '0123456789abcdefghjkmnpqrstuxy',
            4 => '0123456789ABCDEFGHJKMNPQRSTUXY',
            5 => 'abcdefghjkmnpqrstuxyABCDEFGHJKMNPQRSTUXY',
            6 => '0123456789abcdefghjkmnpqrstuxyABCDEFGHJKMNPQRSTUXY',
            7 => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        ];

        if ($type === 8) {
            return bin2hex(random_bytes($length));
        }

        if ($type === 9) {
            return base64_encode(bin2hex(random_bytes($length)));
        }

        $chars = $arr[$type] ?? $arr[7];
        $hash  = '';
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, strlen($chars) - 1)];
        }

        return $hash;
    }

    /**
     * 下划线转驼峰
     * @param string $camelize_words
     * @param string $separator
     * @return string
     */
    public static function camelize(string $camelize_words, string $separator='_'): string
    {
        return ltrim(str_replace(" ", "", ucwords($separator. str_replace($separator, " ", strtolower($camelize_words)))), $separator);
    }

    /**
     * 驼峰命名转下划线命名
     * @param $camelCaps
     * @param string $separator
     * @return string
     */
    public static function uncamelize($camelCaps, string $separator='_'): string
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }
    
    /**
     * 一围数组整理
     * @param array $arr
     * @param array $keys
     * @param int $type
     * @return array
     */
    public static function combArray(array &$arr, array $keys, int $type = 0): array
    {
        foreach ($arr as $key => $value) {
            if ($type == 0) {
                //剔除
                if (in_array($key, $keys)) {
                    unset($arr[$key]);
                }
            } else {
                //保留
                if (!in_array($key, $keys)) {
                    unset($arr[$key]);
                }
            }
        }

        return $arr;
    }
}
